/*
 * Copyright 2024 KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */

#ifndef _COMMIT_STRING_DBUS_H_
#define _COMMIT_STRING_DBUS_H_

#include <iostream>
#include <memory>

#include <dbus_public.h>
#include <fcitx-utils/dbus/bus.h>
#include <fcitx-utils/dbus/objectvtable.h>
#include <fcitx-utils/dbus/servicewatcher.h>
#include <fcitx/addonfactory.h>
#include <fcitx/addoninstance.h>
#include <fcitx/addonmanager.h>
#include <fcitx/instance.h>

class CommitStringBackend;

class CommitStringDBus final : public fcitx::AddonInstance {
public:
    CommitStringDBus(fcitx::Instance *instance);
    ~CommitStringDBus() override;

    fcitx::Instance *instance() { return instance_; }

    void commitString(const std::string &text);
    void commitStringToCurrentWindow(const std::string &text);
    void commitStringToLastWindow(const std::string &text);

private:
    void initDBusInterface();

private:
    FCITX_ADDON_DEPENDENCY_LOADER(dbus, instance_->addonManager());

private:
    fcitx::Instance *instance_;
    fcitx::dbus::Bus *bus_ = nullptr;
    fcitx::dbus::ServiceWatcher watcher_;
    std::unique_ptr<fcitx::dbus::ServiceWatcherEntry> entry_;
    std::unique_ptr<fcitx::dbus::Slot> slot_;
    std::unique_ptr<CommitStringBackend> commitStringBackend_ = nullptr;
};

class CommitStringDBusFactory : public fcitx::AddonFactory {
public:
    fcitx::AddonInstance *create(fcitx::AddonManager *manager) override {
        FCITX_INFO() << "CommitStringDBusFactory ...";
        return new CommitStringDBus(manager->instance());
    }
};

#endif